"""
@name : lianxi
@author : chenwenying
@projectname: 面向对象
@time : 2022/5/28
"""
# 1、完成用户注册，登录，购物功能
# 2、实现链表的反转
# 作业一：
import pandas as pd
import os
import csv

class User:
    def __init__(self, name, passwd, money):
        self.name = name
        self.passwd = passwd
        self.money = money

    def buy_goods(self, goods, weight):
        if weight > goods.store:
            print("库存不足！")
        else:
            pay = weight*goods.price
            if self.money >= pay:
                self.money -= pay
                goods.store -= weight
                print(f"购买成功，{self.name}剩余{self.money}元，"
                      f"{goods.product_name}剩余库存{goods.store}")
                u1 = {'name': [self.name], 'passwd': [self.passwd], 'money': [self.money]}
                u2 = pd.DataFrame(u1)
                fp1 = pd.read_csv('user_info.csv')
                fp2 = fp1[~fp1['name'].isin([self.name])]
                f_result = pd.concat([fp2, u2], ignore_index=True)
                f_result.to_csv('user_info.csv', mode='w', index=False, header=True)
                print(fp1)

            else:
                print("余额不足")


class Goods:
    def __init__(self, classify, product_name, price, store):
        self.classify = classify
        self.product_name = product_name
        self.price = price
        self.store = store


class Register:
    def __init__(self, name1, passwd1, money1, d1):
        self.name1 = name1
        self.passwd1 = passwd1
        self.money1 = money1
        self.d1 = d1

    def enter_table(self, d1):
        u = pd.read_csv(dir_path)
        if name1 in set(u['name']):
            print('该用户已存在')
            return
        else:
            my_user = pd.DataFrame(d1, index=[0])
            my_user.to_csv(dir_path, mode='a', header=False, index=False)


class Login:
    def __init__(self, name2, passwd2):
        self.name2 = name2
        self.passwd2 = passwd2

    def user_exist(self, name2, passwd2):
        fi = pd.read_csv('user_info.csv')

        a = fi[(fi['name'] == name2) & (fi['passwd'] == int(passwd2))]
        if a.empty:
            print('用户名或密码错误')
            return a
        else:
            print('登录成功！')
            return a


apple = Goods("fruits", "apple", 8, 30)
orange = Goods("fruits", "orange", 4, 100)
food = [apple, orange]


def mkdir(dir_path):
    with open(dir_path, mode='w') as fp:
        my_user = pd.DataFrame(columns=['name', 'passwd', 'money'])
        my_user.to_csv(dir_path, index=False)


while True:
    shopping_card = {}
    print("欢迎来到三乐购物系统".center(50, "*"))
    print("1.注册".center(40, " "))
    print("2.登录".center(40, " "))
    option = input("请输入你的选择: ")

    if option == '1':
        # 存放用户信息的文件
        dir_path = "./user_info.csv"
        # 判断存放用户信息的文件是否存在
        if not os.path.exists(dir_path):
            mkdir(dir_path)
        print("欢迎用户注册".center(40, "*"))
        name1 = input("请输入你的名字：")
        if name1.lower() != 'q':
            passwd1 = input("请输入你的密码：")
            if passwd1.lower() != 'q':
                money1 = input("请输入你的存入金额:")
                if money1.lower() != 'q':
                    d1 = {'name': name1, 'passwd': passwd1, 'money': float(money1)}
                    register1 = Register(name1, passwd1, float(money1), d1)
                    register1.enter_table(d1)
                else:break
            else:break
        else:break

    elif option == '2':
        name2 = input("请输入你的名字：")
        if name2.lower() != 'q':
            passwd2 = input("请输入你的密码：")
            if passwd2.lower() != 'q':
                login2 = Login(name2, passwd2)
                result = login2.user_exist(name2, passwd2)

                if not result.empty:
                    result2 = result.set_index('name')
                    print(result2)
                    money2 = result2['money'][name2]
                    print(money2)
                    user = User(name2, passwd2, money2)
                    print('商场'.center(50, '*'))
                    while True:
                        for goods in food:
                            print(f'产品编号:{food.index(goods)}    产品名字:{goods.product_name}    价格:{goods.price}    库存:{goods.store}')
                        food_num = input("请输入需要购买产品的编号:")
                        if food_num.lower() != 'q':
                            if int(food_num) >= 0 and int(food_num) <= len(food) - 1:
                                w = input("请输入购买产品的重量:")
                                if w.lower() != 'q':
                                    if w.isdigit():
                                        buy = user.buy_goods(food[int(food_num)], int(w))
                                    else:
                                        print("请输入数字")
                                else:
                                    break
                            else:
                                print("请输入正确商品编号")
                        else:
                            break
            else:
                break
        else:
            break

    elif option.lower() == 'q':
        print('欢迎下次光临三乐购物系统'.center(50, '*'))
        break

    else:
        print('请按规定输入')



# 作业二
class ListNode:
    def __init__(self,val,next=None):
        if isinstance(val,int):
            self.val = val
            self.next = next
        elif isinstance(val,list):
            self.val = val[0]
            self.next = None
            head = self
            for i in range(1,len(val)):
                node = ListNode(val[i])
                head.next = node
                head = head.next

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        #用来记录上一个节点
        prev = None
        #保存当前的链表
        curr = head
        while curr != None:
            #记录后一个节点
            nex = curr.next
            #改变节点的指向,反转链表
            curr.next = prev
            prev = curr
            #继续处理后面的链表
            curr = nex
        return prev

l = [1,2,3,4,5]
list_node = ListNode(l)
obj = Solution()
reve_list_node = obj.reverseList(list_node)
while reve_list_node:
    print(reve_list_node.val)
    reve_list_node = reve_list_node.next




